/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package business.service;

import com.star.common.ConfigFactory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;

/**
 *
 * @author loctt
 */
public class MySqlFactory {

    private static final Logger logger = Logger.getLogger(MySqlFactory.class);

    private static final String MYSQL_HOST = ConfigFactory.getParam("mysql", "host");
    private static final String MYSQL_PORT = ConfigFactory.getParam("mysql", "port");
    private static final String MYSQL_NAME = ConfigFactory.getParam("mysql", "dbname");
    private static final String MYSQL_USER = ConfigFactory.getParam("mysql", "username");
    private static final String MYSQL_PASS = ConfigFactory.getParam("mysql", "password");
    
    public static Connection getConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            String connStr = "jdbc:mysql://" + MYSQL_HOST + ":" + MYSQL_PORT + "/" + MYSQL_NAME + "?autoReconnect=true&failOverReadOnly=false&maxReconnects=10&useUnicode=true&characterEncoding=UTF-8";
            return DriverManager.getConnection(connStr, MYSQL_USER, MYSQL_PASS);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        return null;
    }
    
    public static void safeClose(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                logger.error("safeClose.Connection:" + e.getMessage(), e);
            }
        }
    }

    public static void safeClose(ResultSet res) {
        if (res != null) {
            try {
                res.close();
            } catch (SQLException e) {
                logger.error("safeClose.ResultSet:" + e.getMessage(), e);
            }
        }
    }

    public static void safeClose(Statement st) {
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                logger.error("safeClose.Statement:" + e.getMessage(), e);
            }
        }
    }
}
